/**
 * 认证状态管理模块
 */
import { reactive, computed } from 'vue'
import type { UserInfo, LoginCredentials } from '@/utils/auth'
import { UserRole } from '@/utils/auth'
import { AuthStorage } from '@/utils/storage'
import { authAPI } from '@/api/auth'
import type { LoginRequest, LoginResponseData } from '@/api/auth'
import { UserStatus } from '@/api/auth'

// 认证状态接口
interface AuthState {
  user: UserInfo | null
  token: string | null
  refreshToken: string | null
  loginTime: number | null
  expiresIn: number | null
  isAuthenticated: boolean
  loading: boolean
  loginAttempts: number
  lastLoginError: string | null
}

// 创建认证状态
const authState = reactive<AuthState>({
  user: null,
  token: null,
  refreshToken: null,
  loginTime: null,
  expiresIn: null,
  isAuthenticated: false,
  loading: false,
  loginAttempts: 0,
  lastLoginError: null
})

// Getters
export const authGetters = {
  // 当前用户
  currentUser: computed(() => authState.user),

  // 当前角色
  currentRole: computed(() => authState.user?.role || null),

  // 是否已认证
  isAuthenticated: computed(() => authState.isAuthenticated && !!authState.token),

  // 用户ID
  userId: computed(() => authState.user?.id || ''),

  // 用户名
  username: computed(() => authState.user?.username || ''),

  // 显示名称
  displayName: computed(() => authState.user?.name || authState.user?.username || '未知用户'),

  // 头像
  avatar: computed(() => authState.user?.avatar || '/static/logo.png'),

  // 是否为管理员
  isAdmin: computed(() => {
    const role = authState.user?.role
    return role === UserRole.ADMIN || role === UserRole.SCHOOL_ADMIN
  }),

  // 是否为超级管理员
  isSuperAdmin: computed(() => authState.user?.role === UserRole.ADMIN),

  // 是否为学校管理员
  isSchoolAdmin: computed(() => authState.user?.role === UserRole.SCHOOL_ADMIN),

  // 是否为班主任
  isTeacher: computed(() => authState.user?.role === UserRole.TEACHER),

  // 是否为家长
  isParent: computed(() => authState.user?.role === UserRole.PARENT),

  // 学校ID
  schoolId: computed(() => authState.user?.schoolId || ''),

  // 班级ID
  classId: computed(() => authState.user?.classId || ''),

  // 登录错误信息
  loginError: computed(() => authState.lastLoginError),

  // 是否可以登录（防止暴力破解）
  canLogin: computed(() => authState.loginAttempts < 5)
}

// Actions
export const authActions = {
  /**
   * 用户登录
   */
  async login(credentials: LoginCredentials): Promise<boolean> {
    try {
      // 检查登录尝试次数
      if (authState.loginAttempts >= 5) {
        authState.lastLoginError = '登录尝试次数过多，请稍后再试'
        uni.showToast({
          title: authState.lastLoginError,
          icon: 'error'
        })
        return false
      }

      authState.loading = true
      authState.lastLoginError = null

      // 构建登录请求
      const loginRequest: LoginRequest = {
        username: credentials.username,
        password: credentials.password
      }

      // 调用真实API
      const response = await authAPI.login(loginRequest)

      if (response.data) {
        const { token, refreshToken, expiresIn, userInfo } = response.data

        // 处理用户信息中的realName字段（兼容name字段）
        const normalizedUserInfo = {
          ...userInfo,
          realName: userInfo.realName || userInfo.name || userInfo.username,
          // 确保status字段是有效的UserStatus枚举值
          status: (userInfo.status as UserStatus) || UserStatus.ACTIVE
        }

        // 设置认证状态
        this.setAuthState({
          user: normalizedUserInfo,
          token,
          refreshToken,
          expiresIn
        })

        // 重置登录尝试次数
        authState.loginAttempts = 0

        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })

        return true
      } else {
        authState.loginAttempts++
        authState.lastLoginError = response.message || '登录失败，响应数据为空'

        console.error('登录失败 - 响应数据:', response)
        uni.showToast({
          title: authState.lastLoginError,
          icon: 'error'
        })

        return false
      }
    } catch (error: any) {
      console.error('登录失败 - 异常:', error)
      authState.loginAttempts++
      authState.lastLoginError = error.message || '登录失败，请稍后重试'

      uni.showToast({
        title: authState.lastLoginError,
        icon: 'error'
      })

      return false
    } finally {
      authState.loading = false
    }
  },

  /**
   * 设置认证状态
   */
  setAuthState(authData: {
    user: UserInfo
    token: string
    refreshToken?: string
    expiresIn?: number
  }) {
    authState.user = authData.user
    authState.token = authData.token
    authState.refreshToken = authData.refreshToken || null
    authState.loginTime = Date.now()
    authState.expiresIn = authData.expiresIn || null
    authState.isAuthenticated = true

    // 持久化存储
    this.persistAuthState()
  },

  /**
   * 持久化认证状态
   */
  persistAuthState() {
    try {
      if (authState.user && authState.token) {
        AuthStorage.saveAuthInfo(
          authState.token,
          authState.user,
          authState.refreshToken || '',
          authState.expiresIn || 7200
        )
      }
    } catch (error) {
      console.error('持久化认证状态失败:', error)
    }
  },

  /**
   * 用户登出
   */
  async logout() {
    try {
      // 调用后端登出接口
      await authAPI.logout()
      console.log('后端登出接口调用成功')
    } catch (error) {
      console.error('后端登出接口调用失败:', error)
      // 即使后端接口失败，也继续执行前端登出逻辑
    }

    // 清除状态
    authState.user = null
    authState.token = null
    authState.refreshToken = null
    authState.loginTime = null
    authState.expiresIn = null
    authState.isAuthenticated = false
    authState.lastLoginError = null

    // 重置登录尝试次数
    authState.loginAttempts = 0

    // 清除持久化存储
    this.clearAuthStorage()

    uni.showToast({
      title: '已退出登录',
      icon: 'success'
    })

    // 跳转到登录页
    uni.reLaunch({
      url: '/pages/auth/login'
    })
  },

  /**
   * 清除认证存储
   */
  clearAuthStorage() {
    try {
      AuthStorage.clearAuthInfo()
    } catch (error) {
      console.error('清除认证存储失败:', error)
    }
  },

  /**
   * 初始化认证状态（从本地存储恢复）
   */
  initAuthState() {
    try {
      // 使用新的存储工具获取认证信息
      const authInfo = AuthStorage.getAuthInfo()

      if (authInfo.token && authInfo.userInfo) {
        // 检查Token是否过期
        if (!AuthStorage.isLoggedIn()) {
          console.log('Token已过期，清除认证状态')
          this.clearAuthState()
          return
        }

        authState.token = authInfo.token
        authState.user = authInfo.userInfo
        authState.refreshToken = authInfo.refreshToken || null
        authState.loginTime = authInfo.loginTime || null
        authState.expiresIn = authInfo.expiresIn || null
        authState.isAuthenticated = true

        console.log('认证状态已恢复:', authInfo.userInfo)
      }
    } catch (error) {
      console.error('初始化认证状态失败:', error)
      this.clearAuthStorage()
    }
  },

  /**
   * 检查Token是否过期
   */
  isTokenExpired(loginTime: number | null, expiresIn: number | null): boolean {
    if (!loginTime || !expiresIn) return true

    const currentTime = Date.now()
    const expireTime = loginTime + (expiresIn * 1000)

    return currentTime >= expireTime
  },

  /**
   * 检查Token是否即将过期
   */
  isTokenExpiringSoon(): boolean {
    // 使用新的存储工具检查Token是否即将过期
    return AuthStorage.isTokenExpiringSoon()
  },

  /**
   * 刷新Token
   */
  async refreshAuthToken(): Promise<boolean> {
    try {
      const refreshToken = AuthStorage.getRefreshToken()

      if (!refreshToken) {
        console.log('没有刷新Token')
        return false
      }

      console.log('正在刷新Token...')

      // 调用刷新Token API
      const response = await authAPI.refreshToken(refreshToken)

      if (response.data) {
        const { token: newToken, refreshToken: newRefreshToken, expiresIn } = response.data

        // 更新状态
        authState.token = newToken
        authState.refreshToken = newRefreshToken
        authState.loginTime = Date.now()
        authState.expiresIn = expiresIn

        // 更新存储
        AuthStorage.updateToken(newToken, newRefreshToken, expiresIn)

        console.log('Token刷新成功')
        return true
      } else {
        console.log('Token刷新失败:', response.message)
        this.logout()
        return false
      }
    } catch (error) {
      console.error('Token刷新失败:', error)
      this.logout()
      return false
    }
  },

  /**
   * 更新用户信息
   */
  updateUserInfo(updates: Partial<UserInfo>) {
    if (authState.user) {
      authState.user = { ...authState.user, ...updates }
      this.persistAuthState()
    }
  },

  /**
   * 重置登录错误
   */
  resetLoginError() {
    authState.lastLoginError = null
    authState.loginAttempts = 0
  },

  /**
   * 设置加载状态
   */
  setLoading(loading: boolean) {
    authState.loading = loading
  },

  /**
   * 忘记密码 - 发送验证码
   */
  async sendForgotPasswordCode(email: string): Promise<boolean> {
    try {
      authState.loading = true

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))

      console.log('发送重置密码验证码到:', email)

      return true
    } catch (error: any) {
      console.error('发送验证码失败:', error)
      authState.lastLoginError = error.message || '发送验证码失败，请重试'

      uni.showToast({
        title: authState.lastLoginError,
        icon: 'error'
      })

      return false
    } finally {
      authState.loading = false
    }
  },

  /**
   * 忘记密码 - 验证身份
   */
  async verifyForgotPasswordIdentity(username: string, email: string, captcha: string): Promise<boolean> {
    try {
      authState.loading = true

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500))

      console.log('验证身份:', { username, email, captcha })

      return true
    } catch (error: any) {
      console.error('验证身份失败:', error)
      authState.lastLoginError = error.message || '验证身份失败，请重试'

      uni.showToast({
        title: authState.lastLoginError,
        icon: 'error'
      })

      return false
    } finally {
      authState.loading = false
    }
  },

  /**
   * 忘记密码 - 验证邮箱验证码
   */
  async verifyEmailCode(email: string, code: string): Promise<boolean> {
    try {
      authState.loading = true

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))

      console.log('验证邮箱验证码:', { email, code })

      return true
    } catch (error: any) {
      console.error('验证邮箱验证码失败:', error)
      authState.lastLoginError = error.message || '验证码错误，请重试'

      uni.showToast({
        title: authState.lastLoginError,
        icon: 'error'
      })

      return false
    } finally {
      authState.loading = false
    }
  },

  /**
   * 忘记密码 - 重置密码
   */
  async resetPassword(email: string, newPassword: string): Promise<boolean> {
    try {
      authState.loading = true

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 2000))

      console.log('重置密码:', { email, newPassword })

      uni.showToast({
        title: '密码重置成功',
        icon: 'success'
      })

      return true
    } catch (error: any) {
      console.error('重置密码失败:', error)
      authState.lastLoginError = error.message || '重置密码失败，请重试'

      uni.showToast({
        title: authState.lastLoginError,
        icon: 'error'
      })

      return false
    } finally {
      authState.loading = false
    }
  },

  /**
   * 修改密码
   */
  async changePassword(currentPassword: string, newPassword: string): Promise<boolean> {
    try {
      authState.loading = true

      if (!authState.user?.username) {
        throw new Error('用户未登录')
      }

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500))

      console.log('修改密码:', { username: authState.user.username })

      uni.showToast({
        title: '密码修改成功',
        icon: 'success'
      })

      return true
    } catch (error: any) {
      console.error('修改密码失败:', error)
      authState.lastLoginError = error.message || '修改密码失败，请重试'

      uni.showToast({
        title: authState.lastLoginError,
        icon: 'error'
      })

      return false
    } finally {
      authState.loading = false
    }
  },

  /**
   * 清除认证状态（不跳转）
   */
  clearAuthState() {
    authState.user = null
    authState.token = null
    authState.refreshToken = null
    authState.loginTime = null
    authState.expiresIn = null
    authState.isAuthenticated = false
    authState.lastLoginError = null
    authState.loginAttempts = 0

    this.clearAuthStorage()
  }
}

// 导出状态
export { authState }

// 默认导出
export default {
  state: authState,
  getters: authGetters,
  actions: authActions
}